package cn.iocoder.yudao.module.jifenyuan.api.wallet;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.module.jifenyuan.api.wallet.dto.WalletRespDto;
import cn.iocoder.yudao.module.jifenyuan.controller.app.wallet.vo.AppWalletCreateReqVO;
import cn.iocoder.yudao.module.jifenyuan.controller.app.walletlog.vo.AppWalletLogCreateReqVO;
import cn.iocoder.yudao.module.jifenyuan.convert.wallet.WalletConvert;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.wallet.WalletDO;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.walletlog.WalletLogDO;
import cn.iocoder.yudao.module.jifenyuan.enums.JifenyuanWalletLogChangeTypeEnum;
import cn.iocoder.yudao.module.jifenyuan.service.wallet.WalletService;
import cn.iocoder.yudao.module.jifenyuan.service.walletlog.WalletLogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static cn.iocoder.yudao.module.jifenyuan.enums.ErrorCodeConstants.WALLET_COIN_NOT_ENOUGH;

@Service
public class WalletApiImpl implements WalletApi {
    @Resource
    private WalletService walletService;
    @Resource
    private WalletLogService walletLogService;

    @Override
    public boolean createWallet(Long userId, Long defaultCoin) {
        AppWalletCreateReqVO appWalletCreateReqVO = new AppWalletCreateReqVO();
        appWalletCreateReqVO.setUserId(userId);
        appWalletCreateReqVO.setCoin(defaultCoin);
        appWalletCreateReqVO.setVip(false);
        Long wallet = walletService.createWallet(appWalletCreateReqVO);
        return wallet != null;
    }

    @Override
    public WalletRespDto getWalletByUserId(Long userId) {

        return WalletConvert.INSTANCE.convert2(walletService.getWalletByUserId(userId));
    }

    @Override
    public boolean changeWallerCoin(Long userId, Long coin, Integer type, String remark) {

        if (JifenyuanWalletLogChangeTypeEnum.ADD.getStatus().equals(type)) {
            walletService.addWalletCoin(userId, coin);
            //添加流水
            AppWalletLogCreateReqVO  walletLogDO = new AppWalletLogCreateReqVO();
            walletLogDO.setRemark(remark).setUserId(userId).setScore(coin).setType(type);
            walletLogService.createWalletLog(walletLogDO);
            return true;

        } else {
            int i = walletService.reduceWalletCoin(userId, coin);
            if (i > 0) {
                //添加流水
                AppWalletLogCreateReqVO  walletLogDO = new AppWalletLogCreateReqVO();
                walletLogDO.setRemark(remark).setUserId(userId).setScore(coin).setType(type);
                walletLogService.createWalletLog(walletLogDO);
                return true;
            } else {
                throw ServiceExceptionUtil.exception(WALLET_COIN_NOT_ENOUGH);
            }
        }
    }
}
